#include "udt_interface.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>

void udt_inputData(char *fileName, UDTDataLinkSet *pLink)
{
    FILE* fin = fopen(fileName, "r");
    int i, j;
	

	fscanf(fin, "%d %d", &pLink->linkCount, &pLink->attribCount);

    pLink->labelCount = 0;

    for (i = 0; i < pLink->linkCount; ++i) {
        pLink->items[i] = (UDTDataItem*) malloc(sizeof(UDTDataItem));
        fscanf(fin, "%d", &pLink->items[i]->label);
		pLink->items[i]->label--;
        if (pLink->items[i]->label > pLink->labelCount) 
            pLink->labelCount = pLink->items[i]->label;
       
        for (j = 0; j < pLink->attribCount; ++j)  {
            fscanf(fin, "%lf %lf", &pLink->items[i]->attrib[j][0], &pLink->items[i]->attrib[j][1]);
			assert(pLink->items[i]->attrib[j][1] > pLink->items[i]->attrib[j][0] );
			pLink->items[i]->attrib[j][2] = 1.0 / (pLink->items[i]->attrib[j][1] - pLink->items[i]->attrib[j][0]);
            pLink->items[i]->weight = 1;
		};
    };

    pLink->labelCount++;   
	
	printf("Parsing completed, linkCount %d, attribCount %d, labelCount %d\n",
			pLink->linkCount, pLink->attribCount, pLink->labelCount);
    fclose(fin);
};

void udt_inputData_Raw(char *fileName, UDTDataLinkSet *pLink)
{
    FILE* fin = fopen(fileName, "r");
    int i, j, readed;
	char buffer[1000];
    char *pBuf;

    pLink->labelCount = -1;
    pLink->linkCount = 0;

    while (!feof(fin)) {
        i = pLink->linkCount ++;
        pLink->items[i] = (UDTDataItem*) malloc(sizeof(UDTDataItem));
        pLink->items[i]->label = 0;

        fgets(buffer, 1000, fin);
        pBuf = buffer;
        readed = sscanf(pBuf, "%d : ", &pLink->items[i]->label);
        if (readed == 1)
            pBuf = strchr(pBuf, ':')+2;
        
		pLink->items[i]->label--;
        if (pLink->items[i]->label > pLink->labelCount) 
            pLink->labelCount = pLink->items[i]->label;
       

        pLink->attribCount = 0;
 
        while (1) {
            j = pLink->attribCount;
            readed = sscanf(pBuf, "[%lf, %lf]", &pLink->items[i]->attrib[j][0], &pLink->items[i]->attrib[j][1]);
            if (readed != 2) break;
            pLink->attribCount ++;
            pBuf = strchr(pBuf, ']') + 2;            
			pLink->items[i]->attrib[j][2] = 1.0 / (pLink->items[i]->attrib[j][1] - pLink->items[i]->attrib[j][0]);
            pLink->items[i]->weight = 1;
		};

    };

    pLink->labelCount++;   
	printf("Parsing completed, linkCount %d, attribCount %d, labelCount %d\n",
			pLink->linkCount, pLink->attribCount, pLink->labelCount);
    fclose(fin);

};
